package com.mdd.admin.service.crontab.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.google.common.collect.Lists;
import com.google.common.primitives.Doubles;
import com.mdd.admin.service.goods.IGoodsService;
import com.mdd.admin.service.goods.IOrderGoodsService;
import com.mdd.admin.service.order.IOrderService;
import com.mdd.admin.service.refund.IOrderRefundService;
import com.mdd.admin.service.staff.IStaffService;
import com.mdd.common.constant.GlobalConstant;
import com.mdd.common.entity.address.UserAddress;
import com.mdd.common.entity.goods.Goods;
import com.mdd.common.entity.order.Order;
import com.mdd.common.entity.refund.OrderRefund;
import com.mdd.common.entity.staff.Staff;
import com.mdd.common.enums.*;
import com.mdd.common.mapper.address.UserAddressMapper;
import com.mdd.common.mapper.setting.DictDataMapper;
import com.mdd.common.plugin.notice.NoticeDriver;
import com.mdd.common.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author kn4im3
 * @date 2023/3/17 14:45
 */
@Slf4j
@Service(value = "myJob")
@Transactional(rollbackFor = Exception.class)
public class TaskServiceImpl {
	@Resource
	private IOrderService orderService;

	@Resource
	private IOrderRefundService refundService;

	@Resource
	private IStaffService staffService;

	@Resource
	private IOrderGoodsService orderGoodsService;

	@Resource
	private UserAddressMapper userAddressMapper;

	@Resource
	private RedisTemplate<String, Object> redisTemplate;

	@Resource
	private IGoodsService goodsService;

	@Resource
	private DictDataMapper dictDataMapper;


	/**
	 * 从第0秒开始每隔10秒执行1次，派遣师傅
	 */
	public void dispatchConfirm() {
		log.info("dispatchConfirm 被执行......");
		Map<String, String> map = ConfigUtil.get(GlobalConstant.TRANSACTION_SETTING);
		String dispatch = map.get(GlobalConstant.IS_AUTH_DISPATCH);
		Integer on = 1;
		try {
			on = Integer.valueOf(dispatch);
		} catch (Exception e) {
			log.error("系统随机派单配置异常:{}", e);
		}
		if (on == 0) {
			return;
		}
		List<Order> orderList = orderService.getNoStaffByDuration(1);
		if (CollectionUtils.isEmpty(orderList)) {
			return;
		}
		List<Long> orderIds = orderList.stream().map(Order::getId).distinct().collect(Collectors.toList());
		// 查询订单和积分
		Map<Long, Long> orderGoodsMap = orderGoodsService.listByOrderIds(orderIds).stream().collect(Collectors.toMap(item -> item.getOrderId(), item -> item.getGoodsId(), (a, b) -> b));
		for (Order order : orderList) {
			Goods good = goodsService.getById(orderGoodsMap.get(order.getId()));
			// 所有单都是优质单
			qualityOrder(order, good, orderGoodsMap);
		}
	}


	/**
	 * @param result         Result对象
	 * @param finalLongitude 订单的经度
	 * @param finalLatitude  订单的纬度
	 * @return 返回师傅、师傅和订单的距离
	 */
	@NotNull
	private static Map<Staff, BigDecimal> getStaff(Result result, double finalLongitude, double finalLatitude) {
		HashMap<Staff, BigDecimal> hashMap = new LinkedHashMap<>();
		HashMap<Staff, BigDecimal> hashMap1 = new HashMap<>();
		// 判断哪个师傅的距离最短
		if(result.staffList.size() > 1){
			result.staffList.stream().sorted((o1, o2) -> {
				Double distanceByGaoDe1 = RangeCalculationUtil.getDistanceByGaoDe(finalLongitude, finalLatitude, Double.parseDouble(o1.getLongitude()), Double.parseDouble(o1.getLatitude()));
				hashMap1.put(o1, BigDecimal.valueOf(distanceByGaoDe1));
				Double distanceByGaoDe2 = RangeCalculationUtil.getDistanceByGaoDe(finalLongitude, finalLatitude, Double.parseDouble(o2.getLongitude()), Double.parseDouble(o2.getLatitude()));
				hashMap1.put(o2, BigDecimal.valueOf(distanceByGaoDe2));
				if (Doubles.compare(distanceByGaoDe1, distanceByGaoDe2) > 0) {
					return 1;
				} else if (Doubles.compare(distanceByGaoDe1, distanceByGaoDe2) < 0) {
					return -1;
				}
				return 0;
			}).forEach(staff -> {
				BigDecimal bigDecimal = hashMap1.get(staff);
				hashMap.put(staff, bigDecimal);
			});
		} else {
			for (Staff staff : result.staffList) {
				Double distanceByGaoDe1 = RangeCalculationUtil.getDistanceByGaoDe(finalLongitude, finalLatitude, Double.parseDouble(staff.getLongitude()), Double.parseDouble(staff.getLatitude()));
				hashMap.put(staff, BigDecimal.valueOf(distanceByGaoDe1));
			}
		}
		return hashMap;
	}

	/**
	 * @param order 订单
	 * @return 返回订单所在的经纬度和全市的师傅列表
	 */
	@Nullable
	private Result getResult(Order order) {
		// log.warn("系统随机派单订单号 ===> {}", order.getSn());
		// 自动派单给师傅, 从市里面寻找师傅
		List<Staff> staffList = staffService.getByCityId(order.getCityId());
		if (CollectionUtils.isEmpty(staffList)) {
			return null;
		}
		String pcda = "province_id:" + order.getProvinceId() +
				"city_id:" + order.getCityId() +
				"district_id" + order.getDistrictId() +
				"address" + order.getAddress();
		double longitude = 0;
		double latitude = 0;
		// 通过订单中的地址，获取经纬度
		if (redisTemplate.hasKey(pcda)) {
			String result = (String) redisTemplate.opsForValue().get(pcda);
			String[] split = result.split(",");
			longitude = Double.parseDouble(split[0]);
			latitude = Double.parseDouble(split[1]);
		} else {
			HashMap<String, Object> userAddressHash = new HashMap<>();
			userAddressHash.put("province_id", order.getProvinceId());
			userAddressHash.put("city_id", order.getCityId());
			userAddressHash.put("district_id", order.getDistrictId());
			userAddressHash.put("address", order.getAddress());
			userAddressHash.put("is_delete", 0);
			List<UserAddress> userAddresses = userAddressMapper.selectByMap(userAddressHash);
			for (UserAddress userAddress : userAddresses) {
				if (StringUtil.isNotEmpty(userAddress.getLongitude()) && StringUtil.isNotEmpty(userAddress.getLatitude())) {
					String pcda1 = "province_id:" + userAddress.getProvinceId() +
							"city_id:" + userAddress.getCityId() +
							"district_id" + userAddress.getDistrictId() +
							"address" + userAddress.getAddress();
					longitude = Double.parseDouble(userAddress.getLongitude());
					latitude = Double.parseDouble(userAddress.getLatitude());
					redisTemplate.opsForValue().set(pcda1, longitude + "," + latitude);
					break;
				}
			}
		}
		Result result = new Result(staffList, longitude, latitude);
		return result;
	}

	private static class Result {
		public final List<Staff> staffList;
		public final double longitude;
		public final double latitude;

		public Result(List<Staff> staffList, double longitude, double latitude) {
			this.staffList = staffList;
			this.longitude = longitude;
			this.latitude = latitude;
		}
	}

	/**
	 * 从第0秒开始每隔60秒执行1次，关闭超时预约时间的订单
	 */
	public void closeOvertimeOrder() {
		log.info("closeOvertimeOrder 被执行......");
		List<Order> orderInfoList = orderService.getOvertimeOrder();
		for (Order orderInfo : orderInfoList) {
			String orderNo = orderInfo.getSn();
			log.warn("关闭超时预约时间的订单 ===> sn:{}", orderNo);
			//核实订单状态：调用微信支付查单接口
			try {
				orderService.cancelOvertimeOrder(orderNo, 1);
			} catch (Exception e) {
				log.error("关闭超时预约时间的订单:{},异常:{}", orderNo, e);
			}
		}
	}

	/**
	 * 从第0秒开始每隔30秒执行1次，查询创建超过10分钟，并且未支付的订单
	 */
	public void orderConfirm() {
		Map<String, String> map = ConfigUtil.get(GlobalConstant.TRANSACTION_SETTING);
		String timeStr = map.get(GlobalConstant.CANCEL_UNPAID_ORDERS_TIMES);
		log.info("orderConfirm 被执行......");
		// 获取超时的未支付的订单
		Integer time = 10;
		try {
			time = Integer.valueOf(timeStr);
		} catch (Exception e) {
			log.error("orderConfirm,时间设置异常:{}", e);
		}
		List<Order> orderInfoList = orderService.getNoPayOrderByDuration(time);
		for (Order orderInfo : orderInfoList) {
			String orderNo = orderInfo.getSn();
			log.warn("超时订单 ===> sn:{}", orderNo);
			//核实订单状态：调用微信支付查单接口
			try {
				orderService.checkOrderStatus(orderInfo.getId());
			} catch (Exception e) {
				log.error("超时订单 ===>sn:{},   异常:{}", orderNo, e);
				if (e instanceof WxPayException) {
					WxPayException wxPayException = (WxPayException) e;
					if ("ORDER_NOT_EXIST".equals(wxPayException.getErrCode())) {
						orderInfo.setOrderStatus(OrderStatusEnum.CLOSE.getStatus());
						orderInfo.setCancelTime(TimeUtil.timestamp());
						orderInfo.setOrderRemarks("用户未支付订单，后台自动关闭订单。");
						orderService.updateEntityById(orderInfo);
					}
				}
			}
		}
	}

	/**
	 * 从第0秒开始每隔30秒执行1次，查询创建超过5分钟，并且未成功的退款单
	 */
	public void refundConfirm() {
		log.info("refundConfirm 被执行......");
		//找出申请退款超过5分钟并且未成功的退款单
		List<OrderRefund> refundInfoList = refundService.getNoRefundOrderByDuration(1);
		for (OrderRefund refundInfo : refundInfoList) {
			String refundNo = refundInfo.getSn();
			log.warn("超时未退款的退款单号 ===> {}", refundNo);
			try {
				switch (refundInfo.getRefundWay()) {
					case 1:
						//核实订单状态：调用微信支付查询退款接口
						refundService.checkRefundStatus(refundNo);
						break;
					case 2:
						refundService.checkBalanceRefund(refundInfo);
						break;
				}
			} catch (Exception e) {
				log.error("超时未退款的退款单号:{},发生异常:{}", refundNo, e);
			}
		}
	}

	/**
	 * @return void
	 * @Author slien
	 * @Description 从第0秒开始每隔60秒执行1次 系统自动核销订单
	 * @Date 10:54 2023/1/5
	 * @Param []
	 **/
	public void verificationCodeConfirm() {
		log.info("verificationCodeConfirm 被执行......");
		Map<String, String> map = ConfigUtil.get(GlobalConstant.TRANSACTION_SETTING);
		String verificationOrders = map.get(GlobalConstant.VERIFICATION_ORDERS);
		String time = map.get(GlobalConstant.VERIFICATION_ORDERS_TIMES);
		Integer hour = 3;
		Integer on = 1;
		try {
			on = Integer.valueOf(verificationOrders);
			hour = Integer.valueOf(time);
		} catch (Exception e) {
			log.error("系统自动核销订单:{}", e);
		}
		if (on == 0) {
			return;
		}
		orderService.verificationByDuration(hour);
	}


	/**
	 * 设置师傅这8天的体力值
	 */
	public void resetPhysical() {
		List<Staff> allStaff = staffService.list();
		if (redisTemplate.hasKey("send:mobile")) {
			redisTemplate.delete("send:mobile");
		}
		if (CollectionUtil.isEmpty(allStaff)) {
			return;
		}
		allStaff.forEach(staff -> {
			if (staff.getIsDelete().equals(1)) {
				return;
			}
			String redisKey = "staff:id" + staff.getId();
			double physical = 0;
			if (staff.getLevel().equals(StaffLevelEnum.P3.getCode())) {
				physical = StaffLevelEnum.P3.getPhysical();
			} else if (staff.getLevel().equals(StaffLevelEnum.P2.getCode())) {
				physical = StaffLevelEnum.P2.getPhysical();
			} else {
				physical = StaffLevelEnum.P1.getPhysical();
			}
			LocalDate now = LocalDate.now();
			if (redisTemplate.hasKey(redisKey)) {
				// 删除前一天的，并且添加最后一天的key
				redisTemplate.opsForHash().delete(redisKey, now.plusDays(-1).toString());
				redisTemplate.opsForHash().put(redisKey, now.plusDays(7).toString(), physical);
				return;
			}
			for (int i = 0; i <= 7; i++) {
				redisTemplate.opsForHash().put(redisKey, now.plusDays(i).toString(), physical);
			}
		});
	}

	/**
	 * 该方法是用来处理优质单的逻辑
	 *
	 * @param order 订单信息
	 */
	private void qualityOrder(Order order, Goods goods, Map<Long, Long> orderGoodsMap) {
		Result result = getResult(order);
		if (result == null) return;
		double finalLongitude = result.longitude;
		double finalLatitude = result.latitude;
		// 有序的linkedhashmap集合，根据距离来进行排序
		Map<Staff, BigDecimal> staff = getStaff(result, finalLongitude, finalLatitude);
		BigDecimal multiply = goods.getIntegral().multiply(BigDecimal.valueOf(order.getTotalNum()));
		// 只要把积分消耗完就可以了
		double v = multiply.doubleValue();

		BigDecimal maxDistance = BigDecimal.valueOf(10000);
		BigDecimal minDistance = BigDecimal.ZERO;

		List<Staff> finishStaff = new ArrayList<>();
		StringBuilder staffIds = new StringBuilder();
		StringBuilder staffNames = new StringBuilder();
		StringBuilder staffMobiles = new StringBuilder();

		// 记录师傅需要完成几单
		Map<Long, BigDecimal> map = new HashMap<>();
		long currentTimeMillis = System.currentTimeMillis();
		String sn = order.getSn();
		// 分割字符串
		String firstFourChars = sn.substring(0, 6); // 获取前四个字符
		String lastFourChars = sn.substring(sn.length() - 6); // 获取后四个字符
		mark:
		for (; v > 0; ) {
			// 订单寻找了5秒的师傅，还没找到师傅，则结束这个订单,留给其他订单去操作
			if (System.currentTimeMillis() - currentTimeMillis > 5000) {
				Staff staff1 = staffService.getOne(new LambdaQueryWrapper<Staff>().eq(Staff::getMobile, "16674666691"));
				addMethod(staff1, staffIds, staffNames, staffMobiles, finishStaff);
				break mark;
//				if (!redisTemplate.hasKey("send:mobile")) {
//					try {
//						redisTemplate.opsForValue().set("send:mobile", "true");
//						String mobile = ConfigUtil.get("website", "contactPhone", "");
//						Map<String, String> config = new LinkedHashMap<>();
//						config.put("scene", String.valueOf(NoticeEnum.P_ORDER_NotCONSUMED.getCode()));
//						config.put("mobile", mobile);
//						Map<String, String> params = new LinkedHashMap<>();
//						params.put("num1", firstFourChars);
//						params.put("num2", lastFourChars);
//						(new NoticeDriver()).handle(config, params);
//					} catch (Exception e){
//						log.error("系统错误", e);
//					}
//				}
			}
			// 筛选10公里里面的所有师傅
			List<Staff> staffList = new ArrayList<>();
			List<Staff> collect = new ArrayList<>();
			if(staff.entrySet().size() != 1) {
				for (Map.Entry<Staff, BigDecimal> staffBigDecimalEntry : staff.entrySet()) {
					if (staffBigDecimalEntry.getValue().compareTo(maxDistance) <= 0 && staffBigDecimalEntry.getValue().compareTo(minDistance) >= 0) {
						staffList.add(staffBigDecimalEntry.getKey());
					}
				}
				// 进行等级的排序
				collect = staffList.stream().sorted((o1, o2) -> {
					int i1 = 0;
					int i2 = 0;
					i1 = getI(o1);
					i2 = getI(o2);
					return Integer.compare(i2, i1);
				}).collect(Collectors.toList());
			} else {
				for (Map.Entry<Staff, BigDecimal> staffBigDecimalEntry : staff.entrySet()) {
					collect.add(staffBigDecimalEntry.getKey());
				}
			}

			// 开始师傅的消耗积分
			for (Staff staff1 : collect) {
				if (v <= 0) {
					break mark;
				}
				double physical = 0;
				String[] goodsIdsStr = staff1.getGoodsIds().split(",");
				List<Long> goodsIds = Lists.newArrayList();
				for (String idStr : goodsIdsStr) {
					Long goodsId = Long.valueOf(idStr);
					goodsIds.add(goodsId);
				}
				Long l = orderGoodsMap.get(order.getId());
				// 判断师傅是否有该服务
				if (!goodsIds.contains(l)) {
					continue;
				}
				try {
					// 查看师傅是否可以接单，返回true可以接单，返回false不可以接单
					if (orderService.qualityOrder(order.getId(), staff1.getId(), 1)) {
						// 获取redis的key
						String redisKey = "staff:id" + staff1.getId();
						LocalDate localDate = null;
						if (redisTemplate.hasKey(redisKey)) {
							Long seconds = order.getAppointTimeStart();
							// 将秒数转换为 Instant
							Instant instant2 = Instant.ofEpochSecond(seconds);

							// 从 Instant 中获取 LocalDateTime
							LocalDateTime localDateTime = LocalDateTime.ofInstant(instant2, ZoneOffset.UTC);

							// 从 LocalDateTime 中获取 LocalDate
							localDate = localDateTime.toLocalDate();
							physical = (double) redisTemplate.opsForHash().get(redisKey, localDate.toString());
						}

						// 查看当前师傅的等级，如果是P3，则最多扣除6积分，如果是P2，则最多扣除5积分，如果是P1，则最多扣除4积分
						if (staff1.getLevel().equals(StaffLevelEnum.P3.getCode())) {
							if (v >= 6 && physical >= 6) {
								v -= 6;
								physical -= 6;
								// 计算6个积分对应多少单
								BigDecimal divide = new BigDecimal(6).divide(goods.getIntegral(), RoundingMode.CEILING);
								map.put(staff1.getId(), divide);
								addMethod(staff1, staffIds, staffNames, staffMobiles, finishStaff);
							} else if (v < 6 && physical >= v) {
								BigDecimal divide = new BigDecimal(v).divide(goods.getIntegral(), RoundingMode.CEILING);
								physical -= v;
								v = 0;
								// 计算需要做多少单
								map.put(staff1.getId(), divide);
								addMethod(staff1, staffIds, staffNames, staffMobiles, finishStaff);
							}
							// 如果师傅积分不足以接订单，则跳出循环
						} else if (staff1.getLevel().equals(StaffLevelEnum.P2.getCode())) {
							if (v >= 5 && physical >= 5) {
								v -= 5;
								physical -= 5;
								BigDecimal divide = new BigDecimal(5).divide(goods.getIntegral(), RoundingMode.CEILING);
								map.put(staff1.getId(), divide);
								addMethod(staff1, staffIds, staffNames, staffMobiles, finishStaff);
							} else if (v < 5 && physical >= v) {
								BigDecimal divide = new BigDecimal(v).divide(goods.getIntegral(), RoundingMode.CEILING);
								map.put(staff1.getId(), divide);
								physical -= v;
								v = 0;
								addMethod(staff1, staffIds, staffNames, staffMobiles, finishStaff);
							}
						} else if (staff1.getLevel().equals(StaffLevelEnum.P1.getCode())) {
							if (v >= 4 && physical >= 4) {
								BigDecimal divide = new BigDecimal(4).divide(goods.getIntegral(), RoundingMode.CEILING);
								map.put(staff1.getId(), divide);
								v -= 4;
								physical -= 4;
								addMethod(staff1, staffIds, staffNames, staffMobiles, finishStaff);
							} else if (v < 4 && physical >= v) {
								BigDecimal divide = new BigDecimal(v).divide(goods.getIntegral(), RoundingMode.CEILING);
								map.put(staff1.getId(), divide);
								physical -= v;
								v = 0;
								addMethod(staff1, staffIds, staffNames, staffMobiles, finishStaff);
							}
						}
						redisTemplate.opsForHash().put(redisKey, localDate.toString(), physical);
					}
				} catch (Exception e) {
					log.error("当前师傅不能接单，请选择其他师傅", e);
				}
			}

			// 继续增加10公里进行查找
			minDistance = maxDistance;
			maxDistance = maxDistance.add(BigDecimal.valueOf(10000));
		}
		Integer isDispatch = order.getIsDispatch();

		log.info("接单的师傅 ===> {}", finishStaff);
		// 更新订单的接单师傅
		staffService.updateBatchById(finishStaff);
		staffNames.deleteCharAt(staffNames.length() - 1);
		// 更新订单
		order.setStaffIds(staffIds.deleteCharAt(staffIds.length() - 1).toString());
		order.setIsDispatch(OrderDispatchEnum.IS_DISPATCH.getStatus());
		order.setUpdateTime(TimeUtil.timestamp());
		order.setOrderStatus(OrderStatusEnum.SERVICING.getStatus());
		order.setVerificationStatus(OrderVerificationStatusEnum.WAIT_VERIFICATION.getStatus());
		order.setVerificationCode(SnUtils.get6RandomCode());
		order.setUpdateTime(TimeUtil.timestamp());
		orderService.updateEntityById(order);

		log.info("接单的师傅 ===> {}", staffNames.toString());

		// 发送短信通知
		// 发送通知 (订单派单成功通知: 平台)
		Object dispatchLimit = RedisUtil.get("dispatch:limit:" + order.getId());
		if (isDispatch == 0 && dispatchLimit == null) {
			RedisUtil.set("dispatch:limit:" + order.getId(), 1, 60);

			for (Staff staff1 : finishStaff) {
//				try {
//					String phone = ConfigUtil.get("website", "contactPhone", "");
//					if (!phone.equals("")) {
//						String time = TimeUtil.timestampToDate(order.getAppointTimeStart());
//
//						Map<String, String> pConfig = new LinkedHashMap<>();
//						pConfig.put("scene", String.valueOf(NoticeEnum.P_ORDER_DISPATCH.getCode()));
//						pConfig.put("mobile", phone);
//
//						Map<String, String> pParams = new LinkedHashMap<>();
//						pParams.put("order_sn", snBak);
//						pParams.put("staff_name", staffNames.toString());
//						pParams.put("time", time);
//						(new NoticeDriver()).handle(pConfig, pParams);
//					}
//				} catch (Exception ignored) {
//				}

				// 发送通知 (订单确认服务通知: 师傅)
				try {
					Map<String, String> config = new LinkedHashMap<>();
					config.put("scene", String.valueOf(NoticeEnum.F_ORDER_STAY_CONFIRM.getCode()));
					config.put("mobile", staff1.getMobile());
					Map<String, String> params = new LinkedHashMap<>();
					params.put("staff_name", staff1.getName());
					params.put("goods_name", goods.getName());
					params.put("order_number", String.valueOf(map.get(staff1.getId())));
					(new NoticeDriver()).handle(config, params);
				} catch (Exception ignored) {
				}
			}

		}

	}

	private static void addMethod(Staff staff1, StringBuilder staffIds, StringBuilder staffNames, StringBuilder staffMobiles, List<Staff> finishStaff) {
		staffIds.append(staff1.getId() + ",");
		staffNames.append(staff1.getName() + ",");
		staffMobiles.append(staff1.getMobile() + ",");
		staff1.setUpdateTime(TimeUtil.timestamp());
		finishStaff.add(staff1);
	}

	/**
	 * @param o2 师傅
	 * @return 返回师傅的等级大小
	 */
	private int getI(Staff o2) {
		int i2;
		if (o2.getLevel().equals(StaffLevelEnum.P3.getCode())) {
			if (o2.getIsFreelance() == 0) {
				i2 = 6;
			} else {
				i2 = 5;
			}
		} else if (o2.getLevel().equals(StaffLevelEnum.P2.getCode())) {
			i2 = 4;
		} else {
			i2 = 3;
		}
		return i2;
	}
}
